import React, { useState, useEffect } from 'react';
import { Navbar as BootstrapNavbar, Nav, Container, Button } from 'react-bootstrap';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import AuthService from '../services/AuthService';

const Navbar = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [isAdmin, setIsAdmin] = useState(false);
  const [username, setUsername] = useState('');
  const navigate = useNavigate();
  const location = useLocation(); // 获取当前路由信息

  const checkLoginStatus = () => {
    const user = AuthService.getCurrentUser();
    console.log('Navbar检测登录状态:', user, '路径:', location.pathname);
    
    // 更健壮的登录检测
    const loggedIn = AuthService.isAuthenticated();
    setIsLoggedIn(loggedIn);
    
    if (loggedIn) {
      // 设置用户名显示
      if (user.user && user.user.username) {
        setUsername(user.user.username);
      } else if (user.username) {
        setUsername(user.username);
      }
      
      // 使用AuthService.isAdmin()检查是否为管理员
      const adminStatus = AuthService.isAdmin();
      setIsAdmin(adminStatus);
    } else {
      setIsAdmin(false);
      setUsername('');
    }
    
    console.log('登录状态:', loggedIn, '管理员:', isAdmin, '用户名:', username);
  };

  // 监听路由变化
  useEffect(() => {
    console.log('路由变化，重新检查登录状态');
    checkLoginStatus();
  }, [location.pathname]); // 当路径变化时重新检查

  // 初始检查和localStorage变化监听
  useEffect(() => {
    checkLoginStatus();
    
    // 监听localStorage变化
    window.addEventListener('storage', checkLoginStatus);
    
    // 添加自定义事件监听
    window.addEventListener('login-state-change', checkLoginStatus);

    return () => {
      window.removeEventListener('storage', checkLoginStatus);
      window.removeEventListener('login-state-change', checkLoginStatus);
    };
  }, []);

  const handleLogout = () => {
    AuthService.logout();
    setIsLoggedIn(false);
    setIsAdmin(false);
    setUsername('');
    navigate('/login');
    
    // 触发自定义事件通知状态变化
    window.dispatchEvent(new Event('login-state-change'));
  };

  return (
    <BootstrapNavbar bg="success" variant="dark" expand="lg" style={{padding: '0.5rem 0'}}>
      <Container fluid className="px-4">
        {location.pathname !== '/login' && location.pathname !== '/register' && (
          <BootstrapNavbar.Brand as={Link} to={isLoggedIn ? (isAdmin ? '/admin' : '/todos') : '/login'}>
            待办事项系统
          </BootstrapNavbar.Brand>
        )}
        <BootstrapNavbar.Toggle aria-controls="basic-navbar-nav" />
        <BootstrapNavbar.Collapse id="basic-navbar-nav">
          <Nav className="me-auto">
            {isLoggedIn && !isAdmin && <Nav.Link as={Link} to="/todos">我的待办</Nav.Link>}
            {isAdmin && <Nav.Link as={Link} to="/admin">管理面板</Nav.Link>}
          </Nav>
          <Nav className="d-flex align-items-center">
            {isLoggedIn ? (
              <div className="d-flex align-items-center gap-3">
                <span className="text-light" style={{ fontSize: '1rem' }}>欢迎，{username}</span>
                <Button 
                  variant="outline-light" 
                  onClick={handleLogout}
                  style={{
                    borderColor: 'white',
                    color: 'white',
                    fontWeight: '500',
                    padding: '0.4rem 1rem',
                    fontSize: '0.95rem',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px'
                  }}
                >
                  <i className="bi bi-box-arrow-right"></i>
                  退出登录
                </Button>
              </div>
            ) : (
              <div style={{display: 'flex', gap: '32px'}}>
                <Nav.Link as={Link} to="/login" style={{color: 'white', fontWeight: 'bold', border: '2.5px solid white', borderRadius: '12px', fontSize: '1.25rem', padding: '10px 36px', minWidth: '120px', textAlign: 'center', background: 'transparent'}} >登录</Nav.Link>
                <Nav.Link as={Link} to="/register" style={{color: 'white', fontWeight: 'bold', border: '2.5px solid white', borderRadius: '12px', fontSize: '1.25rem', padding: '10px 36px', minWidth: '120px', textAlign: 'center', background: 'transparent'}} >注册</Nav.Link>
              </div>
            )}
          </Nav>
        </BootstrapNavbar.Collapse>
      </Container>
    </BootstrapNavbar>
  );
};

export default Navbar; 